package com.iqi.onigao.netty;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class NettyDecoder extends ByteToMessageDecoder {
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		if (in.readableBytes() < 8) {// 消息头有8位，4位表示len，4位表示msgid
			return;
		}
		in.markReaderIndex();
		int length = in.readIntLE();
		if (length < 8 || length > 10 * 1000 * 1024) {
			throw new RuntimeException("length error :" + length);
		}
		if (in.readableBytes() < length - 4) {
			in.resetReaderIndex();
			return;
		}
		in.resetReaderIndex();
		byte[] message = new byte[length];
		in.readBytes(message);
		out.add(message);
		return;
	}

}
